import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'dart:async';

class ZhiShi {
  final String tupian;
  final String biaoqian;

  ZhiShi({required this.tupian, required this.biaoqian});
}

class shiping {
  final String neirong;
  final String dizhi;
  final String fengmian;

  shiping({required this.neirong, required this.dizhi, required this.fengmian});
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _selectedIndex = 0;
  final PageController _pageController = PageController();
  final ScrollController _listScrollController = ScrollController();
  Timer? _autoPlayTimer;
  Timer? _restartTimer;
  bool _isUserInteracting = false;
  final List<ZhiShi> zhishiItems = [
    ZhiShi(tupian: 'assets/images/incisors.png', biaoqian: 'An Incisors'),
    ZhiShi(tupian: 'assets/images/canine.png', biaoqian: 'Canine Teeth'),
    ZhiShi(tupian: 'assets/images/bicuspids.png', biaoqian: 'Bicuspids'),

    ZhiShi(tupian: 'assets/images/molars.png', biaoqian: 'Molars'),
    ZhiShi(tupian: 'assets/images/gums.png', biaoqian: 'Gums'),
    ZhiShi(tupian: 'assets/images/enamel.png', biaoqian: 'Enamel'),
  ];

  final List<shiping> shipingItems = [
    shiping(
      neirong: 'Professional Teeth Whitening: Safe Methods for Brighter Smile',
      dizhi: 'assets/videos/video1.mp4',
      fengmian: 'assets/images/video1.jpg',
    ),
    shiping(
      neirong: 'Daily Oral Care Routine: Prevent Cavities and Gum Disease',
      dizhi: 'assets/videos/video2.mp4',
      fengmian: 'assets/images/video2.jpg',
    ),
    shiping(
      neirong: 'Dental Hygiene Tips: Flossing Techniques for Healthy Gums',
      dizhi: 'assets/videos/video3.mp4',
      fengmian: 'assets/images/video3.jpg',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _startAutoPlay();
  }

  @override
  void dispose() {
    _autoPlayTimer?.cancel();
    _restartTimer?.cancel();
    _pageController.dispose();
    _listScrollController.dispose();
    super.dispose();
  }

  void _startAutoPlay() {
    if (_isUserInteracting) return;
    _autoPlayTimer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (mounted) {
        final nextIndex = (_selectedIndex + 1) % zhishiItems.length;
        _pageController.animateToPage(
          nextIndex,
          duration: const Duration(milliseconds: 500),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  void _stopAutoPlay() {
    _autoPlayTimer?.cancel();
    _autoPlayTimer = null;
  }

  void _restartAutoPlayAfterDelay() {
    _restartTimer?.cancel();
    _restartTimer = Timer(const Duration(seconds: 5), () {
      if (mounted) {
        _isUserInteracting = false;
        _startAutoPlay();
      }
    });
  }

  void _onUserInteraction() {
    _isUserInteracting = true;
    _stopAutoPlay();
    _restartAutoPlayAfterDelay();
  }

  void _onPageChanged(int index) {
    setState(() {
      _selectedIndex = index;
    });
    if (_listScrollController.hasClients) {
      final itemWidth = 143.w + 10.w;
      _listScrollController.animateTo(
        index * itemWidth,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _onListTap(int index) {
    _onUserInteraction();
    _pageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 500),
      curve: Curves.easeInOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // biaoti
                Center(
                  child: Padding(
                    padding: EdgeInsets.only(bottom: 16.h),
                    child: Text(
                      'Grint',
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Rubik One',
                        color: Colors.black87,
                      ),
                    ),
                  ),
                ),

                // 图片
                AspectRatio(
                  aspectRatio: 343 / 276,
                  child: PageView.builder(
                    controller: _pageController,
                    onPageChanged: (index) {
                      _onUserInteraction();
                      _onPageChanged(index);
                    },
                    itemCount: zhishiItems.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 9.h),
                        child: AnimatedContainer(
                          duration: const Duration(milliseconds: 300),
                          child: Image.asset(
                            zhishiItems[index].tupian,
                            fit: BoxFit.contain,
                          ),
                        ),
                      );
                    },
                  ),
                ),

                SizedBox(
                  height: 42.h,
                  child: ListView.builder(
                    controller: _listScrollController,
                    scrollDirection: Axis.horizontal,
                    itemCount: zhishiItems.length,
                    itemBuilder:
                        (context, index) => GestureDetector(
                          onTap: () {
                            _onListTap(index);
                          },
                          child: Container(
                            width: 143.w,
                            decoration: BoxDecoration(
                              color:
                                  _selectedIndex == index
                                      ? AppColors.lightBlue
                                      : AppColors.white,
                              borderRadius: BorderRadius.circular(30.r),
                              border: Border.all(
                                width: 2.w,
                                color:
                                    _selectedIndex == index
                                        ? AppColors.border
                                        : Colors.transparent,
                              ),
                            ),
                            margin: EdgeInsets.only(right: 10.w),
                            child: Center(
                              child: Text(
                                zhishiItems[index].biaoqian,
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.w900,
                                  color: AppColors.black,
                                ),
                              ),
                            ),
                          ),
                        ),
                  ),
                ),

                // dental
                Padding(
                  padding: EdgeInsets.fromLTRB(16.w, 16.h, 0.w, 0.h),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                      width: 241.w,
                      height: 64.h,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/dental-health.png'),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ),
                ),

                // diet guide
                GestureDetector(
                  onTap: () {
                    context.push('/home/guide');
                  },
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 9.h),
                    child: Image.asset(
                      'assets/images/diet-guide.png',
                      fit: BoxFit.cover,
                      width: double.infinity,
                    ),
                  ),
                ),

                // science
                GestureDetector(
                  onTap: () {
                    context.push('/home/science');
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 16.w, right: 16.w),
                    child: Image.asset(
                      'assets/images/science.png',
                      fit: BoxFit.cover,
                      width: double.infinity,
                    ),
                  ),
                ),

                // teeth cleaning
                Padding(
                  padding: EdgeInsets.fromLTRB(16.w, 16.h, 0.w, 9.h),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                      width: 241.w,
                      height: 64.h,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/teeth-cleaning.png'),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ),
                ),

                // tips 的列表
                ListView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: shipingItems.length,
                  itemBuilder:
                      (context, index) => GestureDetector(
                        onTap: () async {
                          final result = await context.push(
                            '/home/video-detail',
                            extra: {
                              'videoPath': shipingItems[index].dizhi,
                              'videoContent': shipingItems[index].neirong,
                              'coverImage': shipingItems[index].fengmian,
                              'viewCount': 1366 + index * 567,
                              'videoId': 'video_${index + 1}', // 添加视频ID
                            },
                          );

                          // 处理举报删除视频的结果
                          if (result != null &&
                              result is Map<String, dynamic>) {
                            if (result['action'] == 'delete_video') {
                              _deleteVideo(
                                result['videoPath'],
                                result['videoId'],
                              );
                            }
                          }
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            color: AppColors.white,
                            borderRadius: BorderRadius.circular(27.r),
                          ),
                          margin: EdgeInsets.only(
                            left: 16.w,
                            right: 16.w,
                            bottom: 8.h,
                          ),
                          child: Row(
                            children: [
                              Expanded(
                                flex: 160,
                                child: Container(
                                  height: 104.h,
                                  decoration: BoxDecoration(
                                    image: DecorationImage(
                                      image: AssetImage(
                                        shipingItems[index].fengmian,
                                      ),
                                      fit: BoxFit.cover,
                                    ),
                                    borderRadius: BorderRadius.circular(27.r),
                                  ),
                                  child: Center(
                                    child: Icon(
                                      IconFontIcons.iconPlayFill,
                                      color: AppColors.white,
                                      size: 18.sp,
                                    ),
                                  ),
                                ),
                              ),

                              SizedBox(width: 18.w),

                              Expanded(
                                flex: 183,
                                child: Container(
                                  child: Column(
                                    children: [
                                      Text(
                                        shipingItems[index].neirong,
                                        maxLines: 3,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                ),
                              ),

                              SizedBox(width: 13.w),
                            ],
                          ),
                        ),
                      ),
                ),

                SizedBox(height: 20.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _deleteVideo(String? videoPath, String? videoId) {
    if (videoPath != null) {
      setState(() {
        shipingItems.removeWhere((video) => video.dizhi == videoPath);
      });
    }
  }
}
